var express = require('express');
var router = express.Router();

var axios = require('axios')

const { UsersModel, TicketOrdersModel, CardOrdersModel, TicketInfoModel, CardInfoModel } = require('../utils/model')
const { createToken, checkToken } = require('../utils/token')

/* GET users listing. */
router.get('/test', function(req, res, next) {
  res.send('测试----------------------');
});

// 注册
router.post('/register', function (req, res, next) {
  console.log(req.body);
  var { phone, username } = req.body;
  UsersModel.findOne({
    $or: [
      { username },
      { phone }
    ]
  }).then(data => {
    console.log(data, "注册");
    if (data) {
      if (req.body.phone == data.phone) {     
        res.json({
            code: 402,
            data: null,
            msg: '注册失败，手机号已被注册'
        })
      }
      if (req.body.username == data.username) {     
        res.json({
            code: 402,
            result: null,
            msg: '注册失败，用户名已存在',
        })
      }
    } else {
      req.body.time = new Date();
      req.body.avatar = 'public\\avatar\\default-avatar.png';
      UsersModel.insertMany(req.body)
        .then(result => {
          console.log(result);
          res.json({
            code: 200,
            data: result[0],
            msg: '注册成功'
          })
        })
    }
  })
})

// 登陆
router.post('/login', (req, res) => {
  var { username, password, type } = req.body;
  if (type == 1) {
    UsersModel.findOne({
      username
    }).then(result => {
      if (result) {
        console.log(result, "登陆密码");
        if (password == result.password) {
          res.json({
            code: 200,
            data: result,
            msg: '登陆成功'
          })
        } else {
          res.json({
            code: 402,
            data: null,
            msg: '登陆失败，密码输入错误'
          })
        }
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '登陆失败，用户名不存在',
      })
      }
    })
  }
})

// 查询手机号是否已注册
router.post('/haveRegister', (req, res) => {
  var { phone } = req.body;
    UsersModel.findOne({
      phone
    }).then(result => {
      if (result) {
        res.json({
          code: 200,
          msg: '手机号已被注册'
        })
      } else {
        res.json({
          code: 400,
          msg: '手机号未被注册',
        })
      }
    })
})

// 修改密码
router.post('/changePassword', function (req, res, next) {
  console.log(req.body);
  var { phone, password } = req.body;
  UsersModel.updateMany({
    phone
  },
  {
    $set: {
      password
    }
  }).then(data => {
    if (data) {
      res.json({
          code: 200,
          data: null,
          msg: '修改密码成功'
      })
    } else {
      res.json({
        code: 400,
        data: result[0],
        msg: '修改密码失败'
      })
    }
  })
})

// 发送验证码
router.get('/sendcaptcha', (req, res) => {
  console.log(req.query);
  var { phone, type } = req.query;
  if (type == '1') {  // 注册
    // 发送验证码
    axios.get('http://47.104.209.44:3333/captcha/sent', {
      params: {
          phone
      }
  })
    .then(result => {
        console.log(result.data, "发送验证码响应信息");
        if (result.data.code == 200) {
            res.json({
                code: 200,
                ...result.data,
                msg: '验证码发送成功',
            })
        }
    })
    .catch(err => {
      console.log(err);
      res.json({
          code: 500,
          err,
          msg: '服务器异常',
      })
    })
  } else if (type == '2') {  // 登陆
    UsersModel.findOne({
        phone
    })
      .then(data => {
          if (data) {
              // 发送验证码
              axios.get('http://47.104.209.44:3333/captcha/sent', {
                  params: {
                      phone
                  }
              })
                  .then(result => {
                      // console.log(result.data);
                      if (result.data.code == 200) {
                          res.json({
                              code: 200,
                              ...result.data,
                              msg: '验证码发送成功',
                          })
                      }
                  })
          } else {
              res.json({
                  code: 402,
                  msg: '发送失败，手机号未注册',
              })
          }
      })
      .catch(err => {
          console.log(err);
          res.json({
              code: 500,
              err,
              msg: '服务器异常',
          })
      })
  }
})

// 校验验证码
router.get('/verifycaptcha', (req, res) => {
  var { phone, captcha, type } = req.query;
  if (type == 1) {  // 注册验证
    // 校验验证码
    axios.get('http://47.104.209.44:3333/captcha/verify', {
      params: {
          phone, captcha
      }
  })
    .then(result => {
      console.log(result.data);
      if (result.data.code == 200) {
          res.json({
              code: 200,
              ...result.data,
              msg: '验证码校验成功',
          })
      }
    })
    .catch(err => {
      console.log(err);
      res.json({
          code: 402,
          msg: '验证码填写错误，请重新输入',
      })
    })
  } else if (type == 2) { //登陆验证
    UsersModel.findOne({
        phone
    })
      .then(data => {
        console.log(data, "登录验证码");
        if (data) {
            // 校验验证码
            axios.get('http://47.104.209.44:3333/captcha/verify', {
                params: {
                    phone, captcha
                }
            })
              .then(result => {
                  console.log(result.data);
                  var token = createToken({ phone, time: new Date() })
                  if (result.data.code == 200) {
                      res.json({
                        code: 200,
                        data,
                        result: result.data,
                        msg: '验证码校验成功',
                        token
                      })
                  }
              })
              .catch(err => {
                  console.log(err);
                  res.json({
                    code: 402,
                    data: null,
                    msg: '验证码填写错误，请重新输入',
                  })
              })
          } else {
            res.json({
                code: 402,
                msg: '发送失败，手机号未注册',
            })
          }
      })
      .catch(err => {
        console.log(err);
        res.json({
            code: 500,
            err,
            msg: '服务器异常',
        })
      })
  }
})

// 存储门票订单详情
router.post('/ticketOrders', (req, res) => {
  console.log(req.body);
  TicketOrdersModel.insertMany(req.body)
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: null,
        msg: '门票购买成功'
      })
    })
})

// 存储年卡订单详情
router.post('/cardOrders', (req, res) => {
  console.log(req.body);
  CardOrdersModel.insertMany(req.body)
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: null,
        msg: '年卡购买成功'
      })
    })
})

// 查询用户门票信息
router.post('/showTicketOrders', (req, res) => {
  console.log(req.body);
  TicketOrdersModel.find({ phone: req.body.phone })
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: result,
        msg: '查询用户年卡信息成功'
      })
    })
})

// 查询年卡订单详情
router.post('/showCardOrders', (req, res) => {
  console.log(req.body);
  CardOrdersModel.find({ phone: req.body.phone })
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: result,
        msg: '查询用户年卡信息成功'
      })
    })
})

// 删除已到期的门票订单
router.post('/deleteTicketOrders', (req, res) => {
  console.log(req.body, '删除已到期的门票订单');
  TicketOrdersModel.deleteOne({ _id: req.body._id })
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: null,
        msg: '删除门票订单成功'
      })
    })
})

// 删除已到期的年卡
router.post('/deleteCardOrders', (req, res) => {
  console.log(req.body, '删除已到期的年卡');
  CardOrdersModel.deleteOne({ _id: req.body._id })
    .then(result => {
      console.log(result);
      res.json({
        code: 200,
        data: null,
        msg: '删除年卡成功'
      })
    })
})

// 上传头像
const multer = require('multer');  // 上传文件需要用到的插件
var storage = multer.diskStorage({   // diskStorage 硬盘存储 
    destination: function (req, file, cb) {
      cb(null, './public/avatar')    // 文件路径 
    },
    filename: function (req, file, cb) {  // 文件名 
        cb(null, Date.now() + "zk" + file.originalname)  // file.originalname 文件的原始名字
    }
})
var upload = multer({ storage: storage }).any()  // any 不限定文件 数量

router.post('/sendavatar', upload, (req, res) => {
  console.log(req.files, req.body, "文件");
  const path = req.files[0].path;
  UsersModel.updateMany({
      $or: [{ phone: req.body.phone }, { username: req.body.username }]
  }, {
      $set: {
          avatar: path
      }
  })
      .then(result => {
          console.log(result, 1212);
          res.json({
              code: 200,
              msg: '上传成功',
              avatar: path,
              result
          })
      })
      .catch(err => {
          console.log(err);
          res.json({
              code: 500,
              err,
              msg: '服务器异常',
          })
      })
})

// 获取所有用户账号
router.post('/manageSystemUser', (req, res) => {
    UsersModel.find().then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '登陆成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '查询失败',
      })
      }
    })
})

// 获取所有门票订单
router.post('/manageSystemTicketOrder', (req, res) => {
  TicketOrdersModel.find().then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '查询门票订单成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '查询门票订单失败',
      })
      }
    })
})

// 获取所有年卡订单
router.post('/manageSystemCardOrder', (req, res) => {
  CardOrdersModel.find().then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '查询年卡订单成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '查询年卡订单失败',
      })
      }
    })
})

// 获取门票信息
router.post('/manageSystemTicketInfo', (req, res) => {
  TicketInfoModel.find().then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '查询门票信息成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '查询门票信息失败',
      })
      }
    })
})

// 修改门票价格
router.post('/manageSystemTicketPriceChange', (req, res) => {
  TicketInfoModel.updateMany({
    _id: req.body.id
  },
  {
    $set: {
      ticketPrice: req.body.price,
      updateTime: req.body.updateTime
    }
  }).then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '门票价格修改成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '门票价格修改失败',
      })
      }
    })
})

// 获取年卡信息
router.post('/manageSystemCardInfo', (req, res) => {
  CardInfoModel.find().then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '查询年卡信息成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '查询年卡信息失败',
      })
      }
    })
})

// 修改年卡价格
router.post('/manageSystemCardPriceChange', (req, res) => {
  CardInfoModel.updateMany({
    _id: req.body.id
  },
  {
    $set: {
      cardPrice: req.body.price,
      updateTime: req.body.updateTime
    }
  }).then(result => {
      if (result) {
          res.json({
            code: 200,
            data: result,
            msg: '年卡价格修改成功'
          })
      } else {
        res.json({
          code: 402,
          data: result,
          msg: '年卡价格修改失败',
      })
      }
    })
})

module.exports = router;
